package ink.metoo.gude.module.mail.service.impl

import ink.metoo.gude.module.mail.service.MailService
import ink.metoo.gude.util.logger
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Primary
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.stereotype.Service
import java.io.File
import java.util.*

@Service
@Primary
@ConditionalOnProperty("spring.mail.host")
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
class MailServiceImpl(
    private val javaMailSender: JavaMailSender,
    private val springMailProperties: org.springframework.boot.autoconfigure.mail.MailProperties,
    private val mailAdditionalProperties: ink.metoo.gude.properties.MailProperties,
) : MailService {

    private val log = logger()

    override fun send(
        subject: String,
        to: Array<String>,
        cc: Array<String>,
        bcc: Array<String>,
        content: String,
        html: Boolean,
        files: Array<File>
    ): Boolean {
        val messageHelper = createMimeMessageHelper()
        messageHelper.setSubject(subject)
        messageHelper.setTo(to)
        messageHelper.setCc(cc)
        messageHelper.setBcc(bcc)
        messageHelper.setText(content, true)
        for (file in files) {
            messageHelper.addAttachment(file.name, file)
        }
        return try {
            javaMailSender.send(messageHelper.mimeMessage)
            log.info("send $subject to: ${to.joinToString()}")
            true
        } catch (e: Exception) {
            log.error("send $subject to: ${to.joinToString()} error: ${e.message}", e)
            return false
        }
    }

    fun createMimeMessageHelper() = MimeMessageHelper(javaMailSender.createMimeMessage(), true).apply {
        val alias = mailAdditionalProperties.alias
        val username = springMailProperties.username
        if (alias.isNullOrBlank()) {
            setFrom(springMailProperties.username)
        } else {
            setFrom("${alias}<${username}>")
        }
        setSentDate(Date())
    }


}